


export const fetchApi = async <T>(
    url: string,
    data?: object,
    method: "GET" | "POST" | "PUT" | "DELETE" = "POST",
    headers: Record<string, string> = {}
): Promise<T> => {
    const response = await fetch(url, {
        method: method,
        headers: {
            "Content-Type": "application/json",
            ...headers,
        },
        body: method === "GET" ? undefined : JSON.stringify(data),
    });

    if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const contentType = response.headers.get("Content-Type");
    if (contentType?.includes("application/json")) {
        return response.json() as Promise<T>;
    }
    return response as any;
};


export const fetchWithAuth = async <T>(
    url: string,
    data?: object,
    method: "GET" | "POST" | "PUT" | "DELETE" = "POST",
    header: Record<string, string> = {}
): Promise<T> => {
    let token = localStorage.getItem('token');
    const refreshToken = localStorage.getItem('refreshToken');

    const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        ...header
    };

    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }

    let response = await fetch(url, {
        method: method,
        headers: headers,
        body: method === "GET" ? undefined : JSON.stringify(data),

    });
    // console.log(response.status)
    // 如果 accessToken 过期，尝试刷新
    if (response.status === 401) {
        if (!refreshToken) {
            window.location.href = "/login";
            localStorage.clear()
            return response.json();
        }

        const newTokens = await refreshAccessToken(refreshToken);
        // console.log(newTokens)
        if (newTokens) {
            const { token, refreshToken } = newTokens.data

            localStorage.setItem('token', token);
            localStorage.setItem('refreshToken', refreshToken);

            // 重新发送请求
            headers['Authorization'] = `Bearer ${token}`;
            response = await fetch(url, {
                method: method,
                headers: headers,
                body: method === "GET" ? undefined : JSON.stringify(data),
            });
        }
    }

    return response.json();
};

/**
 * 刷新 Access Token
 */
const refreshAccessToken = async (refreshToken: string): Promise<{
    data: { token: any; refreshToken: any; }; token: string; refreshToken: string
} | null> => {
    try {
        const response = await fetch('/api/user', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: "refresh", params: { oldRefreshToken: refreshToken } }),
        });

        if (!response.ok) {
            window.location.href = "/login";
            localStorage.clear()
            throw new Error('Failed to refresh token');
        }

        return response.json();
    } catch (error) {
        console.error('Refresh token failed:', error);
        return null;
    }
};
